package com.iot.manager.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.iot.manager.R;
import com.iot.manager.data.models.User;
import com.iot.manager.data.models.UserManager;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.ui.activities.LoginActivity;
import com.iot.manager.ui.activities.UserProfileActivity;
import com.iot.manager.ui.activities.ChangePasswordActivity;
import com.iot.manager.ui.activities.AboutActivity;
import com.iot.manager.utils.SharedPreferencesManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SettingsFragment extends Fragment {
    private TextView tvUsername;
    private TextView tvChangePassword;
    private TextView tvAbout;
    private MaterialButton btnLogout;
    private View progressBar;
    private View errorLayout;
    private View dataLayout;
    private ApiService apiService;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        initViews(view);
        setupListeners();
        loadUserInfo();
        return view;
    }

    private void initViews(View view) {
        tvUsername = view.findViewById(R.id.tv_username);
        tvChangePassword = view.findViewById(R.id.tv_change_password);
        tvAbout = view.findViewById(R.id.tv_about);
        btnLogout = view.findViewById(R.id.btn_logout);
        progressBar = view.findViewById(R.id.progressBar);
        errorLayout = view.findViewById(R.id.errorLayout);
        dataLayout = view.findViewById(R.id.dataLayout);
        apiService = RetrofitClient.getInstance().getApiService();
    }

    private void setupListeners() {
        tvUsername.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), UserProfileActivity.class);
            startActivity(intent);
        });

        tvChangePassword.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ChangePasswordActivity.class);
            startActivity(intent);
        });

        tvAbout.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AboutActivity.class);
            startActivity(intent);
        });

        btnLogout.setOnClickListener(v -> {
            new MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.logout)
                .setMessage(R.string.logout_confirmation)
                .setPositiveButton(R.string.confirm, (dialog, which) -> {
                    SharedPreferencesManager.getInstance(requireContext()).clearLoginInfo();
                    UserManager.getInstance().clearUserInfo();
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    requireActivity().finish();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
        });
    }

    private void loadUserInfo() {
        showLoading(true);
        String token = UserManager.getInstance().getToken();
        Log.d("SettingsFragment", "Current token: " + (token != null ? "not null" : "null"));
        
        if (token != null && !token.isEmpty()) {
            apiService.getCurrentUser().enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    showLoading(false);
                    if (response.isSuccessful() && response.body() != null) {
                        User user = response.body();
                        tvUsername.setText(user.getUsername());
                        showData();
                    } else {
                        Log.e("SettingsFragment", "Failed to get user info: " + response.code());
                        showError("无法加载用户信息: " + response.code());
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    showLoading(false);
                    Log.e("SettingsFragment", "Network error", t);
                    showError("网络错误：" + t.getMessage());
                }
            });
        } else {
            showLoading(false);
            Log.e("SettingsFragment", "No token available");
            showError("未登录");
        }
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        dataLayout.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    private void showError(String message) {
        errorLayout.setVisibility(View.VISIBLE);
        TextView errorText = errorLayout.findViewById(R.id.errorText);
        errorText.setText(message);
        dataLayout.setVisibility(View.GONE);
    }

    private void showData() {
        errorLayout.setVisibility(View.GONE);
        dataLayout.setVisibility(View.VISIBLE);
    }
} 